package com.smartremote.sillyagent;

import java.io.ByteArrayOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;


public class ScreenUtil {
    //private static final String TAG = "ScreenUtil";

    private Context mContext;
    private WindowManager mWindowManager;
    private Display mDisplay;
    private DisplayMetrics mDisplayMetrics;
    private Matrix mDisplayMatrix;

    public ScreenUtil(Context context) {
        mContext = context;
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mDisplay = mWindowManager.getDefaultDisplay();
        mDisplayMetrics = new DisplayMetrics();
        mDisplay.getRealMetrics(mDisplayMetrics);
        mDisplayMatrix = new Matrix();
    }

    public Bitmap screenCapture() {
        // We need to orient the screenshot correctly (and the Surface api seems to take screenshots
        // only in the natural orientation of the device :!)
        mDisplay.getRealMetrics(mDisplayMetrics);
        float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels};
        float degrees = getDegreesForRotation(mDisplay.getRotation());
        boolean requiresRotation = (degrees > 0);
        if (requiresRotation) {
            // Get the dimensions of the device in its native orientation
            mDisplayMatrix.reset();
            mDisplayMatrix.preRotate(-degrees);
            mDisplayMatrix.mapPoints(dims);
            dims[0] = Math.abs(dims[0]);
            dims[1] = Math.abs(dims[1]);
        }

        Bitmap bm = Surface.screenshot((int) dims[0], (int) dims[1]);
        if (requiresRotation) {
            // Rotate the screenshot to the current orientation
            Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels,
                    mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(ss);
            c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
            c.rotate(degrees);
            c.translate(-dims[0] / 2, -dims[1] / 2);
            c.drawBitmap(bm, 0, 0, null);
            c.setBitmap(null);
            bm = ss;
        }

        if (bm == null) {
            return null;
        }

        // Optimizations
        bm.setHasAlpha(false);
        bm.prepareToDraw();
        return bm;
    }

    public byte[] screenCaptureToPNG() {
        Bitmap bmp = this.screenCapture();
        if (bmp != null) {
            return bitmapToPNG(bmp);
        }
        return null;
    }

    public static byte[] bitmapToPNG(Bitmap bm) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (bm.compress(Bitmap.CompressFormat.PNG, 100, os) == true) {
            return os.toByteArray();
        }
        return null;
    }

    /**
      * @return the current display rotation in degrees
      */
    private float getDegreesForRotation(int value) {
        switch (value) {
        case Surface.ROTATION_90:
            return 360f - 90f;
        case Surface.ROTATION_180:
            return 360f - 180f;
        case Surface.ROTATION_270:
            return 360f - 270f;
        }
        return 0f;
    }    
}
